package edu.liu.db;
import javax.swing.*;

import java.awt.Dimension;
import java.awt.event.*;

import sun.reflect.generics.scope.Scope;

public class DBQueryUI extends JFrame implements ActionListener
{
	JTable results;
	JTextArea sql;
	JMenuItem exit,execute;
	DBQueryEngine dbq;
	
	public DBQueryUI()
	{
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("DBQuery 1.0");
		
		dbq=new DBQueryEngine("com.microsoft.jdbc.sqlserver.SQLServerDriver","jdbc:microsoft:sqlserver://www.objectgraph.com:6464;DatabaseName=JavaTest","javatest","javatest");
		
		/*SQL TextBox*/
		sql=new JTextArea();
		JScrollPane scpsql=new JScrollPane(sql);
		
		
		
		/*Results Table*/
		results=new JTable();
		JScrollPane scp=new JScrollPane(results);
		
		/*split Pane*/
		JSplitPane jsp=new JSplitPane(JSplitPane.VERTICAL_SPLIT);
		jsp.setOneTouchExpandable(true);
		jsp.setDividerLocation(100);
		jsp.add(scpsql);
		jsp.add(scp);
		
		/*Add the split pane to center*/
		getContentPane().add(jsp,"Center");
		
		/*Create the menus*/
		
		createMenus();
		
		setSize(500,500);
		setVisible(true);
	}
	
	
	public void createMenus()
	{
		JMenuBar bar=new JMenuBar();
		JMenu file=new JMenu("File");
		exit=new JMenuItem("Exit");
		exit.addActionListener(this);
		file.add(exit);
		
		JMenu run=new JMenu("Run");
		execute=new JMenuItem("Execute");
		execute.addActionListener(this);
		run.add(execute);
		
		bar.add(file);
		bar.add(run);
		
		this.setJMenuBar(bar);
		
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource()==execute)
		{
			if(sql.getText().trim().equals(""))
			{
				JOptionPane.showMessageDialog(this, "Please enter some SQL beofe executing");
				return;
			}
			
			//results.setModel(null);
		
			DisconnectedResultSet drs=null;
			try
			{
				
				drs=dbq.executeQuery(sql.getText());
				results.setModel(drs);
			}
			catch(Exception ex)
			{
				JOptionPane.showMessageDialog(this,ex.toString());
			}
		
		}
		
		else if (e.getSource()==exit)
		{
			System.exit(0);
		}
		
		
	}

}
